<template>
	<view>
		<view>
			<drag-button :isDock="true" :existTabBar="true" @btnClick="addComponent" />
		</view>
		<view>
			<drag-button1 :isDock="true" :existTabBar="true" @btnClick="addComponent1" />
		</view>
		<!-- <button @click="addComponent">新增记账上报</button> -->
		<view v-for="(component, index1) in components" :key="index1">
			<view class="uni-list-cell" style="margin-top: 5%;">
				<view class="uni-list-cell-db">
					<text style="line-height: 100rpx;color: black;">选择上报类型:</text>
					<picker
						style="line-height: 100rpx;color: #BEBEBE;font-size: 32rpx; padding-left: 250px;margin-top: -50px;padding-top: -100px;"
						@change="pick($event,index1)" mode='selector' :value="components[index1].index"
						:range="components[index1].array" class='listPicker'>
						<view v-if="components[index1].dianji == false" style="color: green;">
							{{ components[index1].array[components[index1].index] }}
						</view>
						<view v-if="components[index1].dianji == true" style="color: red;">
							{{ components[index1].array[components[index1].index] }}
						</view>
					</picker>
				</view>
			</view>
			<view>
				<view>金额：</view>
				<view>
					<input type="number" maxlength="20" placeholder="请输入金额" style="border: 1px solid rgba(0, 0, 0, 0.1);
					width: 200px;
					margin-top: -20px;
					margin-left: 50px;" @blur="idChange($event,index1)" />
				</view>
			</view>
			<view class="cell">
				<view class="cell-left">
					<view class="cell-text">照片上传：</view>
					<view class="cell-text" style="color: #8C8C8C;width: 180px;">(最多上传3张图片)</view>
				</view>
				<view class="cell-left">
					<view class="qtpicker">
						<!-- <view>MMMMM</view> -->
						<!-- 选中待上传的图片 -->
						<view class="preImgs" v-for="(val,index2) in components[index1].preImgUrl" :key='index2'>
							<image style="border-radius: 6px;" mode="" :src="val" @click="showImg(val,index2)">
							</image>
							<view v-show="components[index1].isShowDelImgBtn">
								<image class="cuo" mode="" src="../../../static/小关闭.png" @click="delImg(index2,index1)">
								</image>
							</view>

						</view>
						<view v-show="components[index1].isShowAddImgBtn">
							<image style="width: 200rpx;height: 200rpx;margin-left: 13rpx;margin-top: 13rpx;"
								@click="chooseImg(index1)" mode="" src="../../../static/添加图片.png">
							</image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view style="margin-top: 20px;">
			<view>人员：</view>
			<view>
				<input type="text" maxlength="20" placeholder="请输入人员" style="border: 1px solid rgba(0, 0, 0, 0.1);
							width: 200px;
							margin-top: -20px;
							margin-left: 50px;" @input="onInput" />
			</view>
			<view style="font-size: 8px; color: red;text-align: center;">*若人员有多人，请用逗号隔开</view>
		</view>
		<!-- 确定上传到服务器 -->
		<button :disabled="submitForbide" type="primary" style="width: 50%;margin-top: 40px;"
			@click="submitImg">上报确认</button>
		<view v-if="completionStatus == '未完成'" style="margin-left: 35%;margin-top: 3px; font-size: 12px; color: red;">
			今日上报：{{completionStatus}}</view>
		<view v-if="completionStatus == '已完成'" style="margin-left: 35%;margin-top: 3px; font-size: 12px; color: green;">
			今日上报：{{completionStatus}}</view>
	</view>
</template>
<script>
	// 导入并注册
	import dragButton from "@/components/drag-button/drag-button.vue";
	import dragButton1 from "@/components/drag-button/drag-button1.vue";
	import amap from '@/static/js/amap-wx.130.js';
	export default {
		data() {
			return {
				userList: [],
				ama: [],
				journalList: [],
				item: null,
				amapPlugin: null,
				gaodekey: 'a65ca3f7e4c4cf0f17d64768ce74a85e', //高德key,此处的key需要去高德平台申请获取，此key是假的！！！
				address: "", // 已经获取到的位置
				completionStatus: '',
				components: [],
				personnel: "",
				imgNum: 0,
				date: new Date().toISOString(),
			};
		},
		components: {
			dragButton,
			dragButton1
		},
		mounted() {
			let _this = this;
			setInterval(function() {
				_this.date = Date.parse(new Date());
			}, 1000);
		},
		//日记账获取页面数据
		onLoad(option) {
			this.item = JSON.parse(option.item)
			uni.$on('workOrderNumberMsg', (data) => {
				//我把传过来的数据存到了 data 中
				this.userList = data
				//    this.userName = data.data[1]
				// console.log('接收数据',data);
			})
			uni.$emit('send')
			this.getLocation();
			uni.request({
				url: "https://www.smacaftersales.com:443/journal/journal/getJournal",
				// url: "http://192.168.3.7:8080/journal/journal/getJournal",
				method: "POST",
				data: {
					recordingtime: this.dateFormat2(this.date),
					workid: this.item.workid,
					serialnumber: this.item.serialnumber
				},
				header: {
					// "Content-type": "application/x-www-form-urlencoded",
					"Content-type": "application/json",
					// "Content-type": "multipart/form-data"
					// "Content-type": "text/xml"
				},
				success: (res) => {
					this.journalList = res.data

					this.components.push({
						price: 0,
						imageData: '',
						selectedOption: '',
						array: ['请选择'],
						index: 0,
						images: [],
						preImgUrl: [], //本地预览的图片数据
						imgNum: 0, //一共选中了多少张照片,用来限制本次最大上传数量
						afterUploadPath: '', //上传图片后，返回上传后的图片地址入库用
						isShowAddImgBtn: true,
						content: '',
						fault_id: '',
						contentText: '',
						addoredit: 'add',
						editclick: 0, //是否点击了右上角的编辑按钮
						faultConfirmId: '',
						isShowDelImgBtn: true,
						submitForbide: false,
						radiobakcolor: '',
						completionStatus: null,
						dianji: true,
					});
					for (var i = 0; i < this.journalList.data[1].length; i++) {
						this.components[0].array.push(this.journalList.data[1][i].reimbursementtype)
					}
					let s = 0
					// console.log(this.dateFormat2(this.date))
					for (var i = 0; i < this.journalList.data[0].length; i++) {
						if (this.journalList.data[0][i].reimbursementtime.includes(this.dateFormat2(this
								.date))) {
							s++;
						}
					}
					console.log(this.components[0])
					// console.log(s)
					if (s > 0) {
						this.completionStatus = '已完成'
					} else if (s == 0) {
						this.completionStatus = '未完成'
					}
				},
			});

		},
		methods: {
			//获取当前时间
			dateFormat(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
				// return year + "-" + month + "-" + day;
			},
			dateFormat2(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "-" + month + "-" + day;
				// return year + "-" + month + "-" + day;
			},
			onReady() {
				// this.components.push({
				// 		price:0,
				// imageData: '',
				// selectedOption: '',
				// 		array:['请选择'],
				// 		index:0,
				// 		images:[],
				// 		preImgUrl: [], //本地预览的图片数据
				// 		imgNum: 0, //一共选中了多少张照片,用来限制本次最大上传数量
				// 		afterUploadPath: '', //上传图片后，返回上传后的图片地址入库用
				// 		isShowAddImgBtn: true,
				// 		content:'',
				// 		fault_id:'',
				// 		contentText:'',
				// 		addoredit:'add',
				// 		editclick:0,//是否点击了右上角的编辑按钮
				// 		faultConfirmId:'',
				// 		isShowDelImgBtn:true,
				// 		submitForbide:false,
				// 		radiobakcolor:'',
				// 		completionStatus:null,
				// dianji:true,
				// });
			},
			//获取坐标
			getLocation() {
				const _this = this;
				this.amapPlugin = new amap.AMapWX({
					key: this.gaodekey
				});
				uni.showLoading({
					title: '获取信息中'
				});
				// 成功获取位置
				_this.amapPlugin.getRegeo({
					success: (data) => {
						// console.log(data, '当前定位');

						_this.address =
							`${data[0].regeocodeData.addressComponent.city}${data[0].regeocodeData.addressComponent.district}`;

						// _this.address 可根据自己的实际情况修改
						_this.address = `${data[0].regeocodeData.formatted_address}`;
						// 传出
						_this.$emit("lodAddress", _this.address)
						uni.hideLoading();
						this.ama = data
					},
					// 获取位置失败
					fail: (err) => {
						uni.showToast({
							title: "获取位置失败，请重启小程序",
							icon: "error"
						})
					}
				});
			},
			//人员赋值
			onInput(e) {
				console.log(e.target.value)
				this.personnel = e.target.value
			},
			//金额赋值
			idChange(event, index) {
				// const o = event.detail;
				// const inputRule = /(0+)|[\d]+/g //修改inputRule 的值
				// this.$nextTick(function() {
				// this.components[index].price = o.value.replace(inputRule , '');
				// })


				this.components[index].price = event.detail.value;

			},
			//下拉框赋值
			pick(e, index) {
				// console.log(e.target.value)
				this.components[index].dianji = false
				this.components[index].index = e.target.value;
			},
			addComponent() {
				this.components.push({
					price: 0,
					imageData: '',
					selectedOption: '',
					array: this.components[0].array,
					index: 0,
					images: [],
					preImgUrl: [], //本地预览的图片数据
					imgNum: 0, //一共选中了多少张照片,用来限制本次最大上传数量
					afterUploadPath: '', //上传图片后，返回上传后的图片地址入库用
					isShowAddImgBtn: true,
					content: '',
					fault_id: '',
					contentText: '',
					addoredit: 'add',
					editclick: 0, //是否点击了右上角的编辑按钮
					faultConfirmId: '',
					isShowDelImgBtn: true,
					submitForbide: false,
					radiobakcolor: '',
					completionStatus: null,
					dianji: true,
				});
			},
			selectChange(event, index) {
				// 下拉框选项改变时更新数据
				// console.log("没进来吗")
				// console.log(this.components[0].options)
				this.components[index].options.value = event.detail.value;
			},
			chooseImage(event, index) {
				// console.log(event, index)
				// 选择图片
				uni.chooseImage({
					count: 1,
					success: res => {
						res.tempFiles.map(val => {
							//把临时路径添加进数组，渲染到页面
							this.components[index].images.push(val.path)
						})
						// 获取选择的图片数据
						//       const tempFilePaths = res.tempFilePaths;
						// console.log(tempFilePaths)
						//       this.components[index].images.push(tempFilePaths[0]);
						// console.log(this.components)
						// console.log(this.components[index].images)
					}
				});
			},
			getFaultConfirmInfoVue(qry_faultid) {
				// getFaultConfirmInfo({FAULT_ID: qry_faultid})
				// .then((res) => {
				// 	console.log("成功："+res.listDataMap);
				// 	//如果能查询到核实记录，则回显
				// 	if(res.listDataMap.length>0){
				// 		//页面置为编辑状态
				// 		this.addoredit='edit'
				// 		let dataObj = res.listDataMap[0]
				// 		//禁用输入框和图片编辑和是否准确按钮，改变样式
				// 		this.radiobakcolor='background-color: grey;'
				// 		this.$refs["content"].textForbide = true
				// 		this.isShowDelImgBtn=false
				// 		this.submitForbide=true
				// 		//此条记录的id，更新用
				// 		this.faultConfirmId = dataObj.id
				// 		//故障描述
				// 		this.$refs["content"].content = dataObj.confirm_comment
				// 		//是否准确
				// 		this.radio1=dataObj.confirm_type
				// 		let imgPathStr = dataObj.img_path+""
				// 		//每一个文件的文件名：[xxx.jpg,yyy.png]
				// 		let imgPathArr = imgPathStr.split(",")
				// 		//拼接图片回显路径的头：http://localhost:8080/uploadPic/
				// 		let imgHeadPath = res.actionResult.message

				// 		//回显图片
				// 		if(imgPathStr.indexOf(",")!=-1){
				// 			//如果够3张了则隐藏添加图片按钮
				// 			this.imgNum=imgPathArr.length
				// 			if(this.imgNum==3){
				// 				this.isShowAddImgBtn=false
				// 			}
				// 			imgPathArr.forEach((item) => {
				// 				this.preImgUrl.push(imgHeadPath+item)
				// 			})
				// 		}

				// 	}
				// })
			},
			//这个方法很奇怪，在pages.vue里配上buttons，在页面上写上这个方法，点击就可以执行了
			onNavigationBarButtonTap(e) {
				// console.log("点击编辑按钮")
				//启用输入框和图片编辑和是否准确按钮，改变样式
				this.radiobakcolor = ''
				this.editclick = 1
				this.$refs["content"].textForbide = false
				this.isShowDelImgBtn = true
				this.submitForbide = false
				//如果要弹出筛选框
				//this.$refs.popup.open()
			},
			// 选择图片
			chooseImg(index) {
				//如果是之前确认过，但是没点击编辑按钮，则直接return
				if (this.components[index].addoredit == 'edit' && this.components[index].editclick == 0) {
					return
				}
				let that = this
				uni.chooseImage({
					// count:  允许上传的照片数量
					count: 3, //h5无法限制
					// sizeType:  original 原图，compressed 压缩图，默认二者都有
					sizeType: "original，compressed",
					success: function(res) { //选择成功，将图片存入本地临时路径，可删除，可查看，等待上传
						// console.log(res, '选择成功')

						// 如果限制图片大小，则添加判断
						res.tempFiles.map(val => {

							// 判断本次上传限制的图片大小
							if (val.size > 10485760) {
								uni.showToast({
									icon: 'none',
									title: '上传的图片大小不超过10M'
								})
								return
							}

							// 判断本次最多上传多少照片
							that.components[index].imgNum++
							if (that.components[index].imgNum == 3) {
								that.components[index].isShowAddImgBtn = false
								uni.showToast({
									icon: 'none',
									title: '最多上传3张图片'
								})
							}
							if (that.components[index].imgNum > 3) {
								that.components[index].imgNum = 3
								uni.components[index].showToast({
									icon: 'none',
									title: '上传的图片最多不能超过3张'
								})
								return
							}
							//把临时路径添加进数组，渲染到页面
							that.components[index].preImgUrl.push(val.path)
						})
					}
				})
			},
			// 确定上传图片，传到服务器
			submitImg() {
				// 坐标获取

				// console.log(this.components)
				console.log(this.personnel + "=============")
				// console.log(this.dateFormat(this.date))
				// uni.navigateBack({
				//     delta: 1
				// });
				// // 如果没有选择图片则返回，本次需求没有此规则，故注释掉
				// /*
				for (var i = 0; i < this.components.length; i++) {
					if (this.components[i].preImgUrl.length == 0) {
						uni.showToast({
							icon: 'none',
							title: '请选择图片'
						})
						return
					}
					if (this.components[i].price.length == 0) {
						uni.showToast({
							icon: 'none',
							title: '金额不能为空'
						})
						return
					}

					if (this.personnel.length == 0) {
						uni.showToast({
							icon: 'none',
							title: '人员不能为空'
						})
						return
					}
				}

				// 遍历要上传的图片临时地址，进行上传
				for (var i = 0; i < this.components.length; i++) {
					let reimbursementtype = this.components[i].array[this.components[i].index]
					let money = this.components[i].price
					// 获取图片地址的数量，用于实现同步请求
					let len = this.components[i].preImgUrl.length
					// 创建变量，用来创建定时器，用于实现同步请求
					let timer = null
					//阻塞阈值，因为使用定时器实现同步，所以需要防止无限循环，用于实现同步请求
					let threshold = 3000;
					let a = '';
					this.components[i].preImgUrl.map(val => {
						uni.uploadFile({
							url: "https://www.smacaftersales.com:443/journal/journal/fileUpload", //服务器地址
							filePath: val, //存在本地要上传的临时图片地址
							name: 'file', //名字可以随便写
							success(res) { //上传成功的回调函数
								//console.log(res, '上传图片成功')
								a += res.data + ","
							},
							complete: (X) => {
								// 不论success还是fail，都把len-1
								len--;
							},
							fail(res) {
								console.log(res, '上传失败')
								uni.showToast({
									icon: 'none',
									title: '上传失败'
								})
							}
						})
					})
					// 关键部分
					// 通过此部分来延续方法的时长，待到异步的回调执行完毕后则关闭
					// 以防万一，建议设定一个阈值，防止出现意外导致无限循环
					timer = setInterval(() => {
						threshold--;
						console.log(threshold);
						// 只要len结束，将定时器清除
						if (!len || threshold == 0 && !a.contains("Current request is not")) {
							console.log("同步结束")
							// 上传操作完成，消除阻塞
							clearInterval(timer)
							if (reimbursementtype == '请选择') {
								uni.showToast({
									title: '请选择报销类型',
									icon: 'error'
								})
							} else {
								uni.request({
									url: "https://www.smacaftersales.com:443/journal/journal/fillInData",
									method: "POST",
									data: {
										reimbursementtype: reimbursementtype,
										money: money,
										reimbursementtime: this.dateFormat(this.date),
										piecturepath: a,
										workid: this.item.workid,
										serialnumber: this.item.serialnumber,
										location: this.ama[0].name + this.ama[0].desc,
										lat: this.ama[0].latitude,
										lng: this.ama[0].longitude,
										userid: this.userList.userId,
										journalPerson: this.personnel,
									},
									header: {
										// "Content-type": "application/x-www-form-urlencoded",
										"Content-type": "application/json",
										// "Content-type": "multipart/form-data"
										// "Content-type": "text/xml"
									},
									success: (res) => {
										if (res.data.data == 1) {
											uni.showToast({
												title: "日记账上报成功",
												duration: 2000,
												icon: 'success'
											})
											this.timer = setTimeout(() => {
												uni.navigateBack({
													delta: 1
												});
											}, 2000)
										} else {
											uni.showToast({
												title: '出现错误，请重新上传',
												icon: 'error',
												duration: 2000
											})
										}
									}
								});
							}


						}

						// 这个参数一定要写，如果不写在IOS端会报错导致同步失败
					}, 1)
				}
			},
			doSubmitFaultConfirm() {
				//图片路径
				let imgpath = this.components[index].afterUploadPath
				//故障描述
				let fault_comment = this.components[index].$refs["content"].content
				//去掉最后一位逗号
				imgpath = imgpath.substring(0, imgpath.length - 1)
				// console.log("开始数据入库"+imgpath)
				submitFaultConfirm({
						"edit_Id": this.faultConfirmId,
						//故障ID，对应_FI表TYPE为0的线路故障ID
						"FAULT_ID": this.fault_id,
						//是否准确：0/1
						"CONFIRM_TYPE": this.radio1,
						//故障描述
						"CONFIRM_COMMENT": fault_comment,
						//故障核实状态：0/1
						"CONFIRM_STATUS": "1",
						//是编辑还是新增：add/edit
						"ADDOREDIT": this.addoredit,
						"IMG_PATH": imgpath
					})
					.then((res) => {
						uni.showToast({
							icon: 'none',
							title: '故障核实提交成功'
						})
					})
			},
			//删除某张图片，从本地的临时路径图片中, 删除路径即可
			delImg(index2, index) {
				this.components[index].imgNum--;
				this.components[index].preImgUrl.splice(index2, 1)
				if (this.components[index].imgNum < 3) {
					this.components[index].isShowAddImgBtn = true;
				}
			},
			bindTextAreaBlur: function(e) {
				// console.log(e.detail.value)
			},
			changeRadio1() {
				//如果是之前确认过，但是没点击编辑按钮，则直接return
				if (this.components[index].addoredit == 'edit' && this.components[index].editclick == 0) {
					return
				}
				this.components[index].radio1 = 1;
				// console.log("是")
			},
			changeRadio2() {
				//如果是之前确认过，但是没点击编辑按钮，则直接return
				if (this.components[index].addoredit == 'edit' && this.components[index].editclick == 0) {
					return
				}
				this.components[index].radio1 = 2;
				// console.log("否")
			},
			//点击小图查看大图片
			showImg(val, index2) {
				// console.log(val, '点击了')
				let that = this
				uni.previewImage({
					// 对选中的图片进行预览
					urls: that.components[index].preImgUrl, //图片数组  // urls:['','']  图片的地址 是数组形式
					current: index, //当前图片的下标
				})
			},
			//历史记录按钮
			addComponent1() {
				console.log(this.journalList, "*************************************")
				uni.navigateTo({
					url: `/pages/afterSaleVue/journalHistoryList/journalHistoryList?item=${JSON.stringify(this.journalList)}`
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	* {
		box-sizing: border-box;
	}

	.qtpicker {
		width: 100%;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		margin: 0 auto;
		padding: 10rpx 0;

		.preImgs {
			margin: 13rpx;
			position: relative;

			image {
				width: 200rpx;
				height: 200rpx;
			}

			.cuo {
				width: 17pt;
				height: 17pt;
				//line-height: 12px;
				//text-align: center;
				///* font-size: 16px; */
				//border-radius: 50%;
				//background-color: #223E4B;
				//color: #FFFFFF;
				position: absolute;
				right: 0px;
				top: 0px;
			}
		}


		.addImg {
			width: 200rpx;
			height: 200rpx;
			border: 2rpx solid #d4d4d4;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 20rpx;
			background-color: #e2dddd;
			margin-left: 13rpx;
			margin-top: 13rpx;
		}
	}

	.cell {
		height: auto;
		padding-left: 20rpx;
		padding-right: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: flex-start;
		background: #fff;
		//border-bottom: 1px solid #BDD8F6;

		.cell-left {
			display: flex;
			align-items: center;
			padding: 8px;

			.cell-icon {
				width: 50rpx;
				height: 50rpx;
			}

			.cell-text {
				color: #595959;
				font-size: 15px;
				margin-left: 0rpx;

				//width: 180rpx;
			}
		}

		.iconfont {
			font-size: 40rpx;
			color: #999;
		}
	}

	.radio-content {
		height: 40rpx;
		display: flex;
		align-items: center;
	}

	.radio {
		width: 24rpx;
		height: 24rpx;
		border-radius: 50%;
		border: 1rpx solid #CCCCCC;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin: 0rpx 26rpx 0rpx 15rpx;
	}

	.radio-active {
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		background-color: #0079FC;
	}

	.radio-default {
		border: 2rpx solid #0079FC;
	}

	.radio-right {
		margin-left: 36rpx;
	}
</style>